
const loki = require('lokijs');
const log4js = require('log4js');
const logger = log4js.getLogger('ft');
const lfsa = require('lokijs/src/loki-fs-structured-adapter.js');
const {app} = require('electron');

const adapter = new lfsa();

let currentDB = null;

function getDB (callback) {
    if (!currentDB) {
        logger.info('[db 连接数据库]', app.getPath('userData') + '/app.db');
        currentDB = new loki(app.getPath('userData') + '/app.db', {
            adapter : adapter,
            autoload: true,
            autosave: true,
            autoloadCallback : (err) => {
                var entries = currentDB.getCollection("messages");
                if (entries === null) {
                    entries = currentDB.addCollection("messages", {indices: ['time']});
                }
                callback && callback(currentDB);
            }
        });
    } else {
        callback && callback(currentDB);
    }
}
 
module.exports = {
    destroyAll: () => {
        logger.info('[db]', '销毁数据库');
        currentDB.close();
    },
    pushChat: (ip, msg) => {
        getDB(ip, (db) => {
            let coll = db.getCollection("messages");
            if (coll === null) {
                coll = db.addCollection("messages", {indices: ['time']});
            }
            coll.insert(msg);
            db.save();
        });
    },

    list: async (ip, pageSize) => {
        return await new Promise((resolve) => {
            getDB(ip, (db) => {
                let coll = db.getCollection("messages");
                if (coll === null) {
                    coll = db.addCollection("messages", {indices: ['time']});
                }
                let chats = coll.chain().find({}).simplesort('$loki', true).limit(pageSize).data();
                resolve(chats);
            });
        });
    },

    next: async (offset, pageSize) => {
        if (currentDB) {
            let coll = currentDB.getCollection("messages");
            return coll.chain().find({}).simplesort('$loki', true).offset(offset).limit(pageSize).data();
        } else {
            return null;
        }
    },

    /**
     * 更新文件进度
     */
    updateFileProgress: async (ip, hash, progress, sended) => {
        getDB(ip, (db) => {
            let coll = db.getCollection("messages");
            let datas = coll.find({hash});
            if (datas && datas.length) {
                let data = datas[0];
                data.progress = progress;
                data.sended = sended;
                coll.update(data);
                db.save();
            }
        });
    },

    updateFilePath: async (ip, hash, filePath) => {
        getDB(ip, (db) => {
            let coll = db.getCollection("messages");
            let datas = coll.find({hash});
            if (datas && datas.length) {
                let data = datas[0];
                data.path = filePath;
                coll.update(data);
                db.save();
            }
        });
    }
}

